import wxValidate from 'wechat-validate'


Page({
  data: {
    countDownVisible: false,
    moblie: '',
    code: ''
  },
  behaviors: [wxValidate],
  rules: {
    moblie: [{ required: true, message: '请填写手机号！' },
    { pattern: /^1[3-8]\d{9}$/, message: '请填写正确手机号!' }],
    code: [{ required: true, message: '请填写验证码！' },
    { pattern: /^\d{6}$/, message: '请填写正确验证码!' }]
  },
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
  async getSMSCode() {
    const { valid, message } = this.validate('moblie')
    if (!valid) return wx.utils.toast(message)
    this.setData({ countDownVisible: true })
    const res = await wx.http.get('/code', { mobile: this.data.moblie })
    if (res.code !== 10000) return wx.utils.toast('发送验证码失败')
  },
  async submitForm() {
    if (!this.validate()) return
    const res = await wx.http.post('/login', {
      mobile: this.data.moblie,
      code: this.data.code
    })
    if (res.code !== 10000) return wx.utils.toast('登陆失败')
    getApp().settoken('token', res.data.token)
    getApp().settoken('refreshToken', res.data.refreshToken)
    wx.redirectTo({
      url: this.redirectURL
    })
  },
  onLoad({ redirectURL }) {
    this.redirectURL = redirectURL
  }
})
